const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const devMode = process.env.NODE_ENV !== 'production';
const Dotenv = require('dotenv-webpack');
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const dayjs = require('dayjs');
const smp = new SpeedMeasurePlugin();
const CopyWebpackPlugin = require('copy-webpack-plugin');

require('dotenv').config({ path: devMode ? '../.env.development' : '../.env.production' });

module.exports = smp.wrap({
  entry: {
    main: './src/index.tsx',
  },
  output: {
    filename: '[name].[contenthash:5].bundle.js',
    chunkFilename: '[name].[contenthash:5].chunk.js',
    path: path.resolve(__dirname, '../dist'),
    clean: true,
    publicPath: '/',
  }, //输出文件
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        include: path.resolve(__dirname, 'src'),
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'ts-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 10kb
          },
        },
      }, //加载图片资源
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
      }, //加载字体资源
    ],
  },
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'public',
          to: '',
          globOptions: {
            ignore: ['**/index.html'],
          },
        },
      ],
    }),
    new Dotenv({
      path: devMode ? '../.env.development' : '../.env.production', // 根据环境选择 .env 文件
      systemvars: true, // 允许从系统环境变量中读取变量
      silent: true, // 静默模式，不打印加载的环境变量
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/index.html', // 模板文件
      templateParameters: {
        currentTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        appVersion: process.env.APP_VERSION || '0.0.0',
        title: process.env.APP_TITLE || 'Loading~~',
      },
    }),
  ],
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    // 添加alias配置以支持 @ 符号指向 src 目录
    alias: {
      '@': path.resolve(__dirname, '../src'), // 假设src是您的源代码根目录
      components: path.resolve(__dirname, '../src/components'),
      state: path.resolve(__dirname, '../src/state'),
    },
  },
  // optimization: {
  //   runtimeChunk: 'single', //运行时单入口配置
  //   moduleIds: 'deterministic', //模块id配置，哈希
  // },
});
